<?php
namespace App\Services\Admin;

use App\Exceptions\AdminException;
use App\Managers\Admin\AdminGroupManager;
use App\Managers\Admin\AdminRoleManager;
use App\Managers\Admin\AdminRoutesManager;
use App\Managers\Admin\AdminUsersManager;
use App\Models\AdminGroupModel;
use App\Models\AdminRoleModel;
use App\Models\AdminRoutesModel;
use App\Models\AdminUsersModel;
use App\Models\AdminUsersRolesModel;
use App\Services\BaseService;
use App\Util\LoginUtil;

class AdminRoutesService extends BaseService
{
    public function __construct( AdminRoutesManager $model)
    {
        parent::__construct();
        $this->manager = $model;
    }



    /**  获取用户权限 */
    /**
    public function getUserRoutesbak()
    {

        $power = [];
        //获取管理员权限
        $user  = LoginUtil::getUserInfo();
        if(empty($user)){
            return  [];
        }
        $user_id = data_get($user, 'id');
        $role_id = data_get($user, 'role_id');
        $is_open = data_get($user, 'is_open');

        if($is_open == 0){
            $data = AdminRoutesModel::query()->where('is_valid', 1)
                ->select(['id',
                    'path', 'component', 'name', 'pid', 'remark', 'icon'])
                ->get();
        }else{
            $role_routes_id = app(AdminRoleManager::class)->setData(['id'=>$role_id])->show();//查看所属角色的 前端路由
            $menu_id=$role_routes_id['routes_id'];
            if(is_null($menu_id)){
                $menu_id = AdminUsersModel::query()->where('id',$user_id)
                    ->value('routes_id');
            }
            if (!empty($menu_id)) {
                $power = array_merge($power, explode(',',$menu_id));
            }
            //获取角色权限
            $role = AdminRoleModel::query()->select(['id','text','pid','remark','routes_id'])->get()->toArray();  //获取所有角色
            $role = json_decode(json_encode($role),true);
            if (!empty($role) && is_array($role)) {
                foreach ($role as $key => $item) {
                    if ($item['id'] == $role_id) {
                        $power = array_merge($power, explode(',', $item['routes_id']));
                    }
                }

                $child = Tree::findAllChild($role, $role_id); //获取所有子角色
                if (!empty($child)) {
                    foreach ($child as $item) {
                        $power = array_merge($power, explode(',', $item['routes_id']));
                    }
                }
            }

            $power = array_filter($power); //过滤空值
            $power = array_unique($power); //过滤重复的数据

            $data = AdminRoutesModel::query()->whereIn('id', $power)->where('is_valid', 1)
                ->select(['id',
                    'path', 'component', 'name', 'pid', 'remark', 'icon'])
                ->get();
        }
        $data = json_decode(json_encode($data),'true');

        return $data;
    }
     **/
    //用户菜单


    public function getUserRoutes()
    {
        $power = [];
        //获取管理员权限
        $user  = LoginUtil::getUserInfo();
        if(empty($user)){
            return  [];
        }
        $user_id = data_get($user, 'id');

        $is_open = data_get($user, 'is_open');
        if($is_open == 0){
            $data = AdminRoutesModel::query()->where('is_valid', 1)
                ->select(['id',
                    'path', 'component', 'name', 'pid', 'remark', 'icon'])
                ->get();
        }else{
            $routes_ids =$this->getUserRolesList($user_id);

            if (!$routes_ids) return [];

            $group_id = $this->getData("group_id");
            dd($group_id);
            if($group_id){          // 只返回当前租户有权限访问的菜单
                $routes_id = AdminGroupModel::query()->where('id', $group_id)->value('routes_id');

                $routes_ids =  array_intersect($routes_ids, array_filter(explode(',',$routes_id)));
            }

            $power = $routes_ids; //过滤重复的数据
            $data = AdminRoutesModel::query()->whereIn('id', $power)->where('is_valid', 1)
                ->select(['id',
                    'path', 'component', 'name', 'pid', 'remark', 'icon'])
                ->get();
        }
        $data = json_decode(json_encode($data),'true');

        return $data;

    }

    /**  获取用户权限 */
    public function getRoutes()
    {
       $data = AdminRoutesModel::query()->where('is_valid', 1)
                ->select(['id',
                    'path', 'component', 'name', 'pid', 'remark', 'icon','orderby'])
                ->get();
        $data = json_decode(json_encode($data),'true');

        return $data;
    }
    /**  获取用户菜单 */
    public function getUserRolesList($user_id)
    {
//        $role_ids = AdminUsersRolesModel::query()->where('admin_user_id' ,'=', $user_id)->where('is_valid', '=',1)->pluck('role_id')->toArray();
//        if (empty($role_ids)) return [];
//
//        $roles = AdminRoleModel::query()->select(['id','routes_id'])->whereIn('id',$role_ids)->where('is_valid', '=',1)->pluck('routes_id')->toArray();  //
//        if (empty($roles)) return [];

        //组装多个角色的 菜单
//        $one_roles = [];
        $one_roles =  explode(',',implode(",",$roles));

        $one_roles =  array_filter($one_roles);
       return $one_roles;

    }

    /** 设置权限 */
    public function setRoutes($data)
    {
        $this->error = '保存失败';
        $result = false;         //设置成功编辑
        if($data['routes_list'] == ''){
            throw new AdminException("请至少选择一个选项。");
        }
        $routes_id  = $data['routes_list'];
        //设置角色权限
        if (isset($data['role_id'])) {
            /** @var $app AdminRoleManager */
            $app = app(AdminRoleManager::class);
            $result =$app->setData(['id'=>$data['role_id'],'routes_list' => $routes_id])->save();
        }

        //设置用户权限
        if (isset($data['user_id'])) {
            /** @var $app AdminUsersManager */
            $app = app(AdminUsersManager::class);
            $result =$app->setData(['id'=>$data['user_id'],'routes_id' => $routes_id])->save();
        }

        //设置用户权限
        if (isset($data['group_id'])) {
            /** @var $app AdminGroupManager */
            $app = app(AdminGroupManager::class);
            $result = $app->setData(['id'=>$data['group_id'],'routes_list' => $routes_id])->save();

        }

        if ($result !== false) {
            $result = true;
        }
        return $result;
    }

    public function setPower()
    {
        $id = $this->getData('id');
        $menu_id = $this->getData('menu_id');
        $menu_list = $this->getData('menu_list');
        if(empty($id)){
            throw new AdminException("缺少参数");
        }
        $this->setData(['id'=>$id,'menu_list'=>$menu_list,'menu_id'=>$menu_id]);
      return $this->save();
    }


    /**
     * 获取权限菜单
     */
    public function lists($isPage = true){
        if($this->getData('is_page')){
            return parent::lists($isPage);
        }else{
            $this->manager->setData($this->data);
            $data = $this->manager->lists(false);
            //返回tree结构
            $is_tree =$this->getData('is_tree', '');
            if($is_tree){
                $selected =$this->getData('selected', '');
                $type = $this->getData('type', '');
                $data = collect($data)->toArray();
                tree($data, $selected, $type);
            }
            return $data;
        }
    }
}
